/*
 * Alloy Analyzer
 * Copyright (c) 2002 Massachusetts Institute of Technology
 *
 * The Alloy Analyzer is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * The Alloy Analyzer is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with the Alloy Analyzer; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package alloy.util;

import java.util.Iterator;

/**
 * {@link Iterator} that yields all possible combinations of
 * values yielded by a given list of {@link ResettableIterator}s.
 */
public class MultiIter implements ResettableIterator {
    /** The resettable iterators used to get all possible sequences of values. */
    private ResettableIterator[] _iters;

    /**
     * The current sequence of values; {@link #next} always returns this same sequence,
     * which the user must not modify.
     */
    private Object[] _values;

    /**
     * Whether we have already filled {@link #_values} with values from the {@link #_iters}.
     * {@link #next} and {@link #hasNext} processing is different based on this.
     */
    private boolean _firstValueYielded;

    /**
     * 
     */
    public MultiIter(ResettableIterator[] iters_) {
	_iters = iters_;
	_values = new Object[_iters.length];
    }

    public boolean hasNext() {
	if (_firstValueYielded) {
	    for (int i=0; i<_iters.length; i++)
		if (_iters[i].hasNext())
		    return true;
	    return false;
	} else {
	    for (int i=0; i<_iters.length; i++)
		if (!_iters[i].hasNext())
		    return false;
	    return true;
	}
    }

    public Object next() {
	if (!_firstValueYielded) {
	    for (int i=0; i<_values.length; i++)
		_values[i] = _iters[i].next();
	    _firstValueYielded = true;
	} else {
	    for (int i=0; i<_iters.length; i++) {
		if (_iters[i].hasNext()) {
		    _values[i] = _iters[i].next();
		    for (int j=0; j<i; j++) {
			_iters[j].rewind();
			_values[j] = _iters[j].next();
		    }
		    break;
		}
	    }
	}
	return _values;
    }

    public void rewind() {
	for (int i=0; i<_iters.length; i++)
	    _iters[i].rewind();
	_firstValueYielded = false;
    }

    public void remove() throws UnsupportedOperationException
    { throw new UnsupportedOperationException("MultiIter.remove()"); }
}
